
'''
目标：绘制收入、成本、收支差异线
准备：
    1. 准备要素集
    2. 准备画布
行为：
    1. 绘制 收入 要素线
    2. 绘制 成本 要素线
    3. 绘制 节点 垂直网格线
    4. 绘制 收支差异线
'''

from ydraw import fin as f
from ydraw import geo
import turtle 

def calc_width_sep(max_total_amount, w_pixel=10800, margin_percent=0.03):
    '''
    计算图形宽度， 左右边距
    max_total_amount: 所有要求中最大的总金额
    w_pixel: 窗体水平最大像素数
    margin_percent: 左右边距在图形宽度中占比
    return: 图形宽度， 左右边距, 缩放比例
    ''' 
    sep = max_total_amount * margin_percent
    image_width = sep + max_total_amount + sep
    scale = w_pixel / image_width
    sep = sep * scale
    image_width = image_width * scale
    
    return image_width, sep, scale
def calc_max_total_amount(elements:list)->float:
    maxes = []
    for element in elements:
        maxes.append(
                sum([
                v['金额']
                for k,v in element.items()    
            ])
        )
    return max(maxes)
def ready_canvas(width, sep,
    w_width=1400, w_height=600,
    w_pixel=10800, margin_percent=0.03,  
    speed=5, 
    ):
    left_bottom_x = -sep
    left_bottom_y = -100
    right_top_x = width-sep
    right_top_y = 500   

    
    turtle.setup(width=w_width, height=w_height)
    # set the coordinates of the turtle window
    turtle.setworldcoordinates(left_bottom_x, left_bottom_y, right_top_x, right_top_y)
    # set the speed of the turtle
    # t.speed(speed)

# 准备要素集
#  速度常量
SLOWER = 1
MIDDLE = 5
FASTER = 10
#  要素
income_value = {
    '已售住宅': {'金额': 120117, '面积': 97889.4},
    '未售住宅': {'金额': 16722, '面积': 17602.27},
    '未售商铺': {'金额': 5727, '面积': 11455.34},
}
cost_value = {
    '落地成本': {'金额': 78000},
    '预计尾款': {'金额': 13000},
    '扩容成本': {'金额': 7200},
}
#  要求中最大总额
max_total_amount = calc_max_total_amount([income_value, cost_value])
#  图形宽度， 左右边距, 缩放比例
width, sep, scale = calc_width_sep(max_total_amount)

# 准备画布
t = turtle.Turtle()

ready_canvas(width=width, sep=sep)
t.speed(SLOWER)
# 绘制 收入 要素线
income = f.AccoElem('收入', income_value,
    scale=scale, thickness=[6, 4, 3], offset=[15, -30, 15])
income.draw()


# 绘制 成本 要素线
cost = f.AccoElem('成本', cost_value, scale, start_dot=geo.Dot(0, 100), color='orange',
offset=[15, -30, 15])
cost.draw()


elements = f.AccoElems([income, cost])
elements.draw_vert_grid_line(bottom_y=-200, top_y=700)
elements.draw()

# hold 住画面
t.hideturtle()
turtle.mainloop()
turtle.done()
